package controler;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.CRN;
import model.beans.CRNBean;
import model.beans.UsuarioBean;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

public class CRNAction extends MappingDispatchAction {
	private final static String DEFAULT = "default";

	public ActionForward teachersList(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {
		ActionForward action_retVal = Validate.validateUser(mapping,request, getResources(request));
		if(action_retVal!=null)return action_retVal;
		
		HttpSession session = request.getSession();
		UsuarioBean user_log_t =(UsuarioBean)session.getAttribute("ses_usuario");
		request.setAttribute("req_crns", CRN.list(user_log_t.getId(), CRN.TEACHER));
		return mapping.findForward(DEFAULT);
	}
	
	public ActionForward studentsList(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {
		ActionForward action_retVal = Validate.validateUser(mapping,request, getResources(request));
		if(action_retVal!=null)return action_retVal;
		
		HttpSession session = request.getSession();
		UsuarioBean user_log_t =(UsuarioBean)session.getAttribute("ses_usuario");
		request.setAttribute("req_crns", CRN.list(user_log_t.getId(), CRN.STUDENT));
		return mapping.findForward(DEFAULT);
	}
	
	public ActionForward studentsByCRN(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		ActionForward action_retVal = Validate.validateUser(mapping,request, getResources(request));
		if(action_retVal!=null)return action_retVal;
		
		String str_crncode = request.getParameter("crn_code");
    	String str_ciclo = request.getParameter("crn_ciclo"); 
    	
    	CRNBean crn_bean = null;
    	HttpSession session = request.getSession();
    	if( str_crncode != null || str_ciclo != null ){
    		crn_bean = CRN.instance(str_crncode, str_ciclo);
    	}else{
    		crn_bean = (CRNBean)session.getAttribute("crn_saveGrades");
    	}
    	
    	session.setAttribute("crn_saveGrades", crn_bean);
    	
    	String materia_tk = crn_bean.getMateria_tk();
    	
    	request.setAttribute("lst_grades", model.Grade.list(materia_tk, null));
		request.setAttribute("crn_bean", crn_bean);
		ArrayList arrL_students = CRN.students(crn_bean);
		arrL_students = CRN.putScored(crn_bean, arrL_students);
		request.setAttribute("req_studentsCrns", arrL_students );
		return mapping.findForward(DEFAULT);
	}
}
